/**
 * @description www
 *
 * @author xiaomi
 */

const koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const ctrls = require('./controllers/www');
const path = require('path');
const views = require('koa-views');

const app = koa();

// init models
app.models = require('./models');

// init views
const viewsPath = path.join(__dirname, '../views/www');
app.use(views(viewsPath, {
    map: {
        html: 'ejs'
    }
}));

// bodyParser
app.use(bodyParser({
    formLimit: '1mb',
    jsonLimit: '1mb'
}));

// builder
if(process.env.NODE_ENV === 'development') {
    const appName = 'www';
    const viewsName = `views/${appName}`;
    const viewsPath = path.join(__dirname, '..', viewsName);
    const PATHS = require('../webpack.paths')({
        appName: appName
    });

    app.use(require('./components/koa-bundler')({
        dllConfigName: 'webpack.dll.config',
        publicPath: PATHS.PUBLIC,
        viewsPath: viewsPath
    }));
}

// init router
app.router = new Router();

// init ctrls
ctrls.forEach(ctrl => ctrl(app, app.router));

// use routers
app.use(app.router.routes());

module.exports = app;
